package org.wu.reggie.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wu.reggie.common.R;
import org.wu.reggie.entity.ShoppingCart;
import org.wu.reggie.service.ShoppingCartService;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     *  作用 获取购物车中的数据
     * @param session
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(HttpSession session){
        // 1 获取登录的用户信息
        Long userId = (Long) session.getAttribute("user");
        // 2 根据用户id查询购物车记录
        List<ShoppingCart> shoppingCartList = shoppingCartService.findCartByUserId(userId);

        return R.success(shoppingCartList);

    }

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart,HttpSession session){

        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);

        shoppingCart = shoppingCartService.add(shoppingCart);

        return R.success(shoppingCart);
    }

    @DeleteMapping("/clean")
    public R<String> clean(HttpSession session){

        // 1 获取当前登录者
        Long userId = (Long) session.getAttribute("user");
        // 2 清空购物车
        shoppingCartService.clean(userId);
        return R.success("清空购物车成功");
    }


}
